package bcp.comun;

import java.security.*;
import java.util.UUID;

import javax.crypto.Cipher; 
import javax.crypto.spec.SecretKeySpec;

import bcp.exceptions.ExceptionClass;
import sun.misc.*;

/**
 * Clase que permite la encriptacion y desencriptacion de claves
 * 
 * @author BCP Team
 * @since Tesis UCE 2009 - 2010
 *
 */
public class EncriptClass {
	
	private static final String ALGORITHM = "AES";
    private static final byte[] keyValue = 
        new byte[] { 'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y' };

    public static String Encrypt(String valueToEnc) throws Exception {
        String encryptedValue = null;
        try {
        	Key key = generateKey();
            Cipher c = Cipher.getInstance(ALGORITHM);
            c.init(Cipher.ENCRYPT_MODE, key);
            byte[] encValue = c.doFinal(valueToEnc.getBytes());
            encryptedValue = new BASE64Encoder().encode(encValue);
		} catch (Exception e) {
			ExceptionClass.SystemException(e.getCause(), e.getStackTrace());
		}
        return encryptedValue;
    }

    public static String Decrypt(String encryptedValue) throws Exception {
    	String decryptedValue = null;
        try {
        	Key key = generateKey();
            Cipher c = Cipher.getInstance(ALGORITHM);
            c.init(Cipher.DECRYPT_MODE, key);
            byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedValue);
            byte[] decValue = c.doFinal(decordedValue);
            decryptedValue = new String(decValue);
		} catch (Exception e) {
			ExceptionClass.SystemException(e.getCause(), e.getStackTrace());
		}
        return decryptedValue;
    }
    
    public static String GetPassword()
    {
    	UUID u = UUID.randomUUID();
    	String passEncode = null;
    	try {
    		String pass = u.toString().substring(0,8);
			passEncode = Encrypt(pass);
		} catch (Exception e) {
			ExceptionClass.SystemException(e.getCause(), e.getStackTrace());
		}
		return passEncode;
    }

    private static Key generateKey() throws Exception {
        Key key = new SecretKeySpec(keyValue, ALGORITHM);
        return key;
    }

	}